﻿using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Masters.Workshops.Commands;

/// <summary>
/// 创建车间命令。
/// </summary>
/// <param name="Workshop"></param>
public record CreateWorkshopCommand(MdWorkshopDto Workshop) : IRequest<IResult<bool>>;

internal sealed class CreateWorkshopCommandHandler(IRepository<MdWorkshop> repo) : IRequestHandler<CreateWorkshopCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateWorkshopCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.WorkshopCode == request.Workshop.WorkshopCode, cancellationToken))
        {
            return Result.Failure("车间编号已存在");
        }

        var workshop = request.Workshop.Adapt<MdWorkshop>();
        var ok = await repo.InsertAsync(workshop, cancellationToken);
        return Result.From(ok);
    }
}
